<?php

namespace App\Http\Controllers;

use App\Models\DeviceDetailedList;
use DB;
use Auth;
use Carbon\Carbon;
use App\Models\Device;
use App\Models\Fans;
use App\Models\User;
use App\Models\Post;
use Validator;
use Illuminate\Http\Request;

class DeviceController extends Controller
{
  public function index(Request $request)
  {
    $perPage = $request->perpage ? $request->perpage : 100;
      $perPage = !is_numeric($perPage) ? 99999 : $perPage;
    $created_at = $request->created_at ? Carbon::parse($request->created_at) : Carbon::today();
    $query = Device::with([
        'deviceDetailed'=> function ($query) use($created_at) {
        $query->where(DB::raw('date(created_at)'), $created_at);
        },
        'posts' => function ($query) use($created_at) {
        $query->where(DB::raw('date(created_at)'), $created_at);
        }, 
        'deviceGroup'
    ]);
    if($request->device_group_id > 0) {
      $query->where('device_group_id', $request->device_group_id);
    }
    $devices = $query->where('device_code','like','%'. $request->device_code .'%')
      ->where('imei','like','%'. $request->imei .'%')
      ->where('phone_number','like','%'. $request->phone_number .'%')
      ->paginate($perPage)
      ->toArray();
    return $this->success(0, '请求成功', $devices);
  }

  public function isMaxed(Request $request)
  {
    $validator = Validator::make($request->all(), [
      'device_id' => 'required|exists:devices,id',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $data = new \stdClass();
    $device = Device::find($request->device_id);
    $user = User::find(1);
    $added_count = $device->posts()
      ->where('request_type', 2)
      ->whereDate('created_at', DB::raw('CURDATE()'))
      ->count();
    $searched_count = $device->posts()
      ->where('request_type', 1)
      ->whereDate('created_at', DB::raw('CURDATE()'))
      ->count();
    $today_card_num = $device->deviceDetailed()
        ->where('detail_type', 12)
        ->whereDate('created_at', DB::raw('CURDATE()'))
        ->first();
    $today_card_num = $today_card_num ? $today_card_num->detail_count : 0;
    $data->added_count = $added_count;
    $data->searched_count = $searched_count;
    $data->card_count = $today_card_num;
    $data->add_is_maxed = ($added_count >= $user->maxed_wechat_request_num) ? true : false;
    $data->search_is_maxed = ($searched_count >= $user->maxed_wechat_search_num) ? true : false;
    $data->card_is_maxed = ($today_card_num >= $user->daily_card_num) ? true : false;
    return $this->success(0, 'OK', $data);
  }

  public function updateMax(Request $request)
  {
    $validator = Validator::make($request->all(), [
      'device_id' => 'required|exists:devices,id',
      'max' => 'required|numeric',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $device = Device::find($request->device_id);
    $device->max = $request->max;
    $device->save();
    return $this->success(0, '设置成功', $device);
  }

  public function createOnline(Request $request)
  {
    $validator = Validator::make($request->all(), [
      'imei' => 'required|between:4,190|alpha_dash',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $imei = substr($request->imei, 0, 32);
    $device = Device::where('imei', $imei)->first();
    if (!$device) {
      $device = new Device();
      $device->status = true;
      $device->imei = $imei;
    }
    $device->online_time = date('Y-m-d H:i:s');
    $device->save();
    if (!$device->status) {
      return $this->failure(-2, '该设备已被禁用，不允许操作');
    }
    return $this->success(0, 'OK', $device);
  }

  public function update(Request $request)
  {
    $validator = Validator::make($request->all(), [
      'id' => 'required|exists:devices',
      'device_code' => 'required',
      'status' => 'required|boolean',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $request->only(['device_code', 'phone_number', 'wechat', 'status']);
    $device = Device::find($request->id);
    $device->device_code = $request->device_code;
    $device->phone_number = $request->phone_number;
    $device->wechat = $request->wechat;
    $device->status = $request->status;
    $device->save();
    return $this->success(0, '更新成功！', $device);
  }

  public function setDeviceGroup(Request $request, $id)
  {
    $device = Device::find($id);
    if(!$device) {
      return $this->failure(-1, '设备不存在');
    }
    $validator = Validator::make($request->all(), [
      'device_group_id' => 'required|exists:device_groups,id',
    ]);
    if($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $device->device_group_id = $request->device_group_id;
    $device->save();
    return $this->success(0, '', $device);
  }

  public function destroy($id)
  {
    Device::find($id)->posts()->delete();
    Device::destroy($id);
    return $this->success(0, '删除成功！');
  }

  public function batchRemove(Request $request)
  {
    $ids = explode(',', $request->ids);
    foreach ($ids as $id) {
      Device::find($id)->posts()->delete();
      Device::destroy($id);
    }
    return $this->success(0, '删除成功！');
  }

    public function setWechatFriend(Request $request, $id)
    {
        $device = Device::find($id);
        if(!$device){
            return $this->failure(-1, '设备不存在');
        }
        $validator = Validator::make($request->all(), [
            'wechat_friend' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->failure(-1, $validator->errors()->first());
        }
        $query = DeviceDetailedList::where('created_at','>=', date('Y-m-d'))
            ->where('device_id',$id)
            ->where('detail_type',10)
            ->first();
        if(!$query){
            $query = new DeviceDetailedList();
            $query->device_id = $id;
            $query->detail_type = 10;
            $query->request_count = 0;
        } 
        $query->detail_count = $request->wechat_friend;
        $query->save();

        return $this->success(0, '');
    }
    public function setAlipayFriend(Request $request, $id)
    {
        $device = Device::find($id);
        if(!$device){
            return $this->failure(-1, '设备不存在');
        }
        $validator = Validator::make($request->all(), [
            'alipay_friend' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->failure(-1, $validator->errors()->first());
        }
        $query = DeviceDetailedList::where('created_at','>=', date('Y-m-d'))
            ->where('device_id',$id)
            ->where('detail_type',11)
            ->first();
        if(!$query){
            $query = new DeviceDetailedList();
            $query->device_id = $id;
            $query->detail_type = 11;
            $query->request_count = 0;
        }
        $query->detail_count = $request->alipay_friend;
        $query->save();

        return $this->success(0, '');
    }

    public function yesterdayFoster(Request $request, $id)
    {
        $device = Device::find($id);
        if(!$device){
            return $this->failure(-1, '设备不存在');
        }
        $query = DeviceDetailedList::where('created_at','>=', date('Y-m-d'))
            ->where('device_id',$device->id)
            ->where('detail_type',15)
            ->first();
        if(!$query) return $this->success(0, '此设备缺失前日数据',false);
        return $this->success(0, '请求成功',$query->detail_count);
    }
}
